package com.outside.landingpage.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.outside.landingpage.dao.LandingPageConfigDao;
import com.outside.landingpage.model.LandingPageConfig;
import com.outside.landingpage.model.RedirectAddress;
import com.outside.landingpage.service.LandingPageConfigService;

import com.outside.landingpage.util.IpAddressUtils;
import com.outside.landingpage.util.LogTool;
import org.apache.log4j.Logger;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;


@Service
public class LandingPageConfigServiceImpl extends ServiceImpl<LandingPageConfigDao, LandingPageConfig> implements LandingPageConfigService {
    private Logger logger = LogTool.getLog("LandingPageConfigService");

    @Resource
    private RestTemplate restTemplate;
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public String findByName(String name) {
        QueryWrapper<LandingPageConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", name);
        LandingPageConfig one = getOne(queryWrapper);
        return JSON.toJSONString(one);
    }

    @Override
    public RedirectAddress verifyCountry(String id, HttpServletRequest request) {
        String userIp = IpAddressUtils.getIpAddress(request);
        String key = "country:" + id + ":" + userIp;
        logger.info("user ip : " + userIp);
        String value = redisTemplate.opsForValue().get(key);
        if (StringUtils.hasText(value)) {
            if (value.equals("access")) {
                return getStaticPath(getLandingPageConfig(id));
            } else {
                return null;
            }
        } else {
            LandingPageConfig landingPageConfig = getLandingPageConfig(id);
            if (Objects.isNull(landingPageConfig)) {
                logger.error("id not found :" + id);
                return null;
            }
            String resStr = restTemplate.getForObject("https://api.ip138.com/ip/?ip=" + userIp + "&datatype=jsonp&token=952b9ba2d58e08212a143c95cc945b0b", String.class);
            logger.info("ipaddress:" + userIp + ",ip rsult:" +resStr);
            if (!StringUtils.hasText(resStr)) {
                logger.error("查询ip返回空， userIp :" +userIp);
                return null;
            }
            JSONObject jsonObject = JSON.parseObject(resStr);
            List<String> data = JSON.parseArray(jsonObject.getString("data"), String.class);
            if (verifyCountry(data, landingPageConfig)) {
                redisTemplate.opsForValue().set(key, "access", 24 * 60 * 60, TimeUnit.SECONDS);
                return getStaticPath(landingPageConfig);
            } else {
                redisTemplate.opsForValue().set(key, "failed", 24 * 60 * 60, TimeUnit.SECONDS);
                return null;
            }
        }
    }

    private boolean verifyCountry(List<String> data, LandingPageConfig landingPageConfig) {
        List<String> strings = JSON.parseArray(landingPageConfig.getAllowCountry(), String.class);
        for (String datum : data) {
            if (strings.contains(datum)) {
                return true;
            }
        }
        return false;
    }

    private RedirectAddress getStaticPath(LandingPageConfig landingPageConfig) {
        if (Objects.isNull(landingPageConfig) || landingPageConfig.getBan()) {
            return null;
        }
        return new RedirectAddress(landingPageConfig.getRegion() + "/page/" + landingPageConfig.getStaticPath(), landingPageConfig.getLink());
    }

    private LandingPageConfig getLandingPageConfig(String id) {
        QueryWrapper<LandingPageConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", id);
        return getOne(queryWrapper);
    }

}
